import mysql, { Pool } from 'mysql2/promise'

const connectionConfig = {
  host: process.env['NEXT_MYSQL_HOST'] || '127.0.0.1',
  port: Number(process.env['NEXT_MYSQL_PORT']) || 3306,
  user: process.env['NEXT_MYSQL_USER'] || 'root',
  password: process.env['NEXT_MYSQL_PASSWORD'] || 'root'
}

const databaseConfig = {
  ...connectionConfig,
  database: process.env['NEXT_MYSQL_DATABASE'] || 'root',
  charset: 'utf8mb4'
}

const createDatabase = async (dbName: string) => {
  try {
    const connection = await mysql.createConnection(connectionConfig)
    await connection.query(
      `CREATE DATABASE IF NOT EXISTS \`${dbName}\` DEFAULT CHARACTER SET = 'utf8mb4';`
    )
    await connection.end()
    console.log(`Database '${dbName}' created or already exists.`)
  } catch (error) {
    console.error(`Error creating database '${dbName}':`, error)
  }
}

const initialConnection = async (): Promise<mysql.Pool> => {
  await createDatabase(databaseConfig.database)

  return mysql.createPool(databaseConfig)
}

export default initialConnection()
